package com.cap.dreamcircle.View;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.baoyz.actionsheet.ActionSheet;
import com.cap.dreamcircle.App.App;
import com.cap.dreamcircle.Base.BaseActivity;
import com.cap.dreamcircle.Consts.Constants;
import com.cap.dreamcircle.Model.Action.DeleteFriendCircleAction;
import com.cap.dreamcircle.Model.Action.LikeDreamCircleAction;
import com.cap.dreamcircle.Model.Bean.BaseBean;
import com.cap.dreamcircle.Model.Bean.DreamCircleUserRecordsBean;
import com.cap.dreamcircle.Model.Bean.DreamCircleUserRecordsEntity;
import com.cap.dreamcircle.Model.Bean.UserInfoBean;
import com.cap.dreamcircle.Model.IDreamModel;
import com.cap.dreamcircle.Model.IFriendModel;
import com.cap.dreamcircle.Model.IUserModel;
import com.cap.dreamcircle.Model.Impl.DreamModelImpl;
import com.cap.dreamcircle.Model.Impl.FriendModelImpl;
import com.cap.dreamcircle.Model.Impl.UserModelImpl;
import com.cap.dreamcircle.R;
import com.cap.dreamcircle.Utils.CommonSubscriber;
import com.cap.dreamcircle.Utils.GlideUtils;
import com.cap.dreamcircle.Utils.PreferenceUtils;
import com.cap.dreamcircle.Utils.SimpleMediaPlayerUtils;
import com.cap.dreamcircle.Utils.ToastUtils;
import com.cap.dreamcircle.Utils.TransformUtils;
import com.cap.dreamcircle.View.Adapter.PersonInfoDreamCircleAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.hdodenhof.circleimageview.CircleImageView;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action0;
import rx.functions.Func2;

/**
 * Created by liucxu on 2017/9/8.
 */

public class PersonalInfoActivity extends BaseActivity {

    @BindView(R.id.layout_back)
    LinearLayout layout_back;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.content_list)
    ListView content_list;
    @BindView(R.id.imv_etc_menu)
    ImageView imv_etc_menu;
    @BindView(R.id.tv_new_dream_record)
    TextView tv_new_dream_record;

    private CircleImageView imv_header;
    private RelativeLayout layout_fellow;
    private ImageView imv_fellow_status;
    private TextView tv_fellow_status;

    private boolean isRefresh = true;
    private int page_index = 1;
    private String userId;
    private List<DreamCircleUserRecordsEntity> datas = new ArrayList<>();

    private IDreamModel dreamModel;
    private IUserModel userModel;
    private IFriendModel friendModel;
    private PersonInfoDreamCircleAdapter adapter;
    private View header_view;

    private String day;

    @Override
    public int getLayoutId() {
        return R.layout.activity_personal_info;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        header_view = View.inflate(this, R.layout.header_user_info_dream_records, null);
        imv_header = (CircleImageView) header_view.findViewById(R.id.imv_header);
        layout_fellow = (RelativeLayout) header_view.findViewById(R.id.layout_fellow);
        imv_fellow_status = (ImageView) header_view.findViewById(R.id.imv_fellow_status);
        tv_fellow_status = (TextView) header_view.findViewById(R.id.tv_fellow_status);
        layout_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                App.GetInstance().finishActivity(PersonalInfoActivity.this);
            }
        });
        dreamModel = new DreamModelImpl();
        userModel = new UserModelImpl();
        friendModel = new FriendModelImpl();
        adapter = new PersonInfoDreamCircleAdapter(this, datas);
        content_list.setAdapter(adapter);
        userId = getIntent().getStringExtra("userId");
        day = getIntent().getStringExtra("Day");
        if (TextUtils.isEmpty(userId)) {
            App.GetInstance().finishActivity(this);
        }
        if(userId.equals(PreferenceUtils.GetUserId())){
            layout_fellow.setVisibility(View.INVISIBLE);
        }
        else{
            layout_fellow.setVisibility(View.VISIBLE);
        }
        if (TextUtils.isEmpty(day)) {
            tv_new_dream_record.setVisibility(View.GONE);
            refreshLayout.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(RefreshLayout refreshlayout) {
                    isRefresh = true;
                    requestUserDreamRecord();
                }
            });
            refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
                @Override
                public void onLoadmore(RefreshLayout refreshlayout) {
                    isRefresh = false;
                    requestUserDreamRecord();
                }
            });
            if (!PreferenceUtils.GetUserId().equals(userId)) {
                imv_etc_menu.setVisibility(View.VISIBLE);
            }
            imv_etc_menu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ActionSheet.createBuilder(PersonalInfoActivity.this, getSupportFragmentManager())
                            .setCancelButtonTitle("取消")
                            .setOtherButtonTitles("加入黑名单")
                            .setCancelableOnTouchOutside(true)
                            .setListener(new ActionSheet.ActionSheetListener() {
                                @Override
                                public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
                                }

                                @Override
                                public void onOtherButtonClick(ActionSheet actionSheet, int index) {
                                    forbiddenUser();
                                }
                            }).show();
                }
            });
        } else {
            tv_new_dream_record.setVisibility(View.VISIBLE);
            tv_new_dream_record.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(PersonalInfoActivity.this, RecordDreamTitleActivcity.class);
                    intent.putExtra("key_history_time",day);
                    startActivity(intent);
                }
            });
            refreshLayout.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(RefreshLayout refreshlayout) {
                    isRefresh = true;
                    requestDreamRecordByDay();
                }
            });
            refreshLayout.setEnableLoadmore(false);
        }
    }

    private void forbiddenUser() {
        friendModel.forbiddenUser(userId).subscribe(new CommonSubscriber<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response) {
                ToastUtils.showShortToast(PersonalInfoActivity.this, "已经成功拉黑");
                App.GetInstance().finishActivity(PersonalInfoActivity.this);
            }

            @Override
            public void onFailure(BaseBean response) {
                ToastUtils.showShortToast(PersonalInfoActivity.this, response.getDesc());
            }
        });
    }

    private void fellowUser(final boolean fellow) {
        Observable<BaseBean> request = null;
        if (fellow) {
            request = friendModel.fellow(userId);
        } else {
            request = friendModel.disFellow(userId);
        }
        request.subscribe(new CommonSubscriber<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response) {
                if (fellow) {
                    tv_fellow_status.setText("已关注");
                    layout_fellow.setEnabled(true);
                    imv_fellow_status.setImageResource(R.mipmap.personal_info_star);
                } else {
                    tv_fellow_status.setText("关注他");
                    imv_fellow_status.setImageResource(R.mipmap.un_fellow);
                    layout_fellow.setEnabled(true);
                }
                layout_fellow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        fellowUser(!fellow);
                    }
                });
            }

            @Override
            public void onFailure(BaseBean response) {
                ToastUtils.showShortToast(PersonalInfoActivity.this, response.getDesc());
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (TextUtils.isEmpty(day)) {
            requestUserDreamRecord();
        } else {
            requestDreamRecordByDay();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        SimpleMediaPlayerUtils.getInstance(this).releaseMediaPlayer();
    }

    @Override
    public void setupData() {
    }

    private void requestDreamRecordByDay() {
        Observable.zip(userModel.RequestUserInfo(), dreamModel.RequestDreamRecordByDay(day), new Func2<UserInfoBean, DreamCircleUserRecordsBean, DreamCircleUserRecordsBean>() {
            @Override
            public DreamCircleUserRecordsBean call(UserInfoBean userInfoBean, DreamCircleUserRecordsBean dreamCircleUserRecordsBean) {
                dreamCircleUserRecordsBean.setHeadImgUrl(Constants.BASE_URL + userInfoBean.getHeadImgUrl());
                dreamCircleUserRecordsBean.setNickName(userInfoBean.getNickName());
                return dreamCircleUserRecordsBean;
            }
        }).compose(TransformUtils.<DreamCircleUserRecordsBean>defaultSchedulers()).subscribe(new Subscriber<DreamCircleUserRecordsBean>() {
            @Override
            public void onCompleted() {
                refreshLayout.finishRefresh();
            }

            @Override
            public void onError(Throwable e) {
                refreshLayout.finishRefresh();
            }

            @Override
            public void onNext(DreamCircleUserRecordsBean response) {
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadmore();
                if ((response.getDreamArray() != null) && (response.getDreamArray().size() > 0)) {
                    GlideUtils.getInstance().LoadContextBitmap(PersonalInfoActivity.this, response.getHeadImgUrl(), imv_header, R.mipmap.default_header, R.mipmap.default_header, GlideUtils.LOAD_BITMAP);
                    tv_title.setText(response.getNickName());
                    if (isRefresh) {
                        datas.clear();
                    }
                    datas.addAll(response.getDreamArray());
                    adapter.setDatas(datas);
                    adapter.notifyDataSetChanged();
                    if (content_list.getHeaderViewsCount() == 0) {
                        content_list.addHeaderView(header_view);
                    }
                } else {
                    refreshLayout.finishLoadmore();
                    App.GetInstance().finishActivity(PersonalInfoActivity.this);
                }
            }
        });
    }


    private void requestUserDreamRecord() {
        int local_page_index = page_index;
        if (isRefresh) {
            local_page_index = 1;
            refreshLayout.setEnableLoadmore(true);
        }
        dreamModel.RequestUserDreamRecord(userId, local_page_index).compose(TransformUtils.<DreamCircleUserRecordsBean>defaultSchedulers()).subscribe(new Subscriber<DreamCircleUserRecordsBean>() {
            @Override
            public void onCompleted() {
                refreshLayout.finishRefresh();
            }

            @Override
            public void onError(Throwable e) {
                refreshLayout.finishRefresh();
                refreshLayout.setEnableLoadmore(false);
            }

            @Override
            public void onNext(DreamCircleUserRecordsBean response) {
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadmore();
                if ((response.getDreamRecord() != null) && (response.getDreamRecord().size() >= 0)) {
                    GlideUtils.getInstance().LoadContextBitmap(PersonalInfoActivity.this, Constants.BASE_URL + response.getHeadImgUrl(), imv_header, R.mipmap.default_header, R.mipmap.default_header, GlideUtils.LOAD_BITMAP);
                    tv_title.setText(response.getNickName());
                    if (response.isFollowed()) {
                        tv_fellow_status.setText("已关注");
                        imv_fellow_status.setImageResource(R.mipmap.personal_info_star);
                        layout_fellow.setEnabled(true);
                        layout_fellow.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                fellowUser(false);
                            }
                        });
                    } else {
                        tv_fellow_status.setText("关注他");
                        layout_fellow.setEnabled(true);
                        imv_fellow_status.setImageResource(R.mipmap.un_fellow);
                        layout_fellow.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                fellowUser(true);
                            }
                        });
                    }

                    if (!PreferenceUtils.GetUserId().equals(userId)) {
                        layout_fellow.setVisibility(View.VISIBLE);
                    } else {
                        layout_fellow.setVisibility(View.INVISIBLE);
                    }

                    if (isRefresh) {
                        datas.clear();
                        page_index = 1;
                    }
                    datas.addAll(response.getDreamRecord());
                    adapter.setDatas(datas);
                    adapter.notifyDataSetChanged();
                    page_index++;
                    if (content_list.getHeaderViewsCount() == 0) {
                        content_list.addHeaderView(header_view);
                    }
                    if (response.getDreamRecord().size() == 0) {
                        refreshLayout.setEnableLoadmore(false);
                    }
                } else {
                    refreshLayout.setEnableLoadmore(false);
                    refreshLayout.finishLoadmore();
                }
            }
        });
    }


    public void onEvent(LikeDreamCircleAction action) {
        likeDreamCircle(action.getDreamId());
    }


    public void onEvent(final DeleteFriendCircleAction action) {
        MaterialDialog dialog = new MaterialDialog.Builder(this).title("提示").content("确定删除?").positiveText("确定").negativeText("取消").onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                DeleteDreamCircleById(action.getDreamId());
            }
        }).build();
        dialog.show();
    }


    private void likeDreamCircle(String dreamId) {
        dreamModel.LikeDreamCircleRecord(dreamId).compose(TransformUtils.<BaseBean>defaultSchedulers()).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new Subscriber<BaseBean>() {
            @Override
            public void onCompleted() {
                hideProgress();
            }

            @Override
            public void onError(Throwable e) {
                hideProgress();
            }

            @Override
            public void onNext(BaseBean res) {
                hideProgress();
                if (res.getCode() == 0) {
                    if (TextUtils.isEmpty(day)) {
                        isRefresh = true;
                        requestUserDreamRecord();
                    } else {
                        requestDreamRecordByDay();
                    }
                } else {
                    ToastUtils.showShortToast(PersonalInfoActivity.this, res.getDesc());
                }
            }
        });
    }

    private void DeleteDreamCircleById(String id) {
        dreamModel.DeleteDreamCircleById(id).compose(TransformUtils.<BaseBean>defaultSchedulers()).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new Subscriber<BaseBean>() {
            @Override
            public void onCompleted() {
                hideProgress();
            }

            @Override
            public void onError(Throwable e) {
                hideProgress();
            }

            @Override
            public void onNext(BaseBean response) {
                hideProgress();
                if (response.getCode() == 0) {
                    if (TextUtils.isEmpty(day)) {
                        isRefresh = true;
                        requestUserDreamRecord();
                    } else {
                        requestDreamRecordByDay();
                    }
                } else {
                    ToastUtils.showShortToast(PersonalInfoActivity.this, response.getDesc());
                }
            }
        });
    }
}
